package algorithmTopics.graph;

import java.util.Map;

/**
 * 前缀树
 *  N叉树
 * @author 86155
 * @date 2025/07/16
 */
class Trie {

    /**
     * 节点 存储字符串
     *
     * @author 86155
     * @date 2025/07/16
     */
    private static class Node{
        Node[] son = new Node[26];
        boolean end;
    }

    /**
     * 根节点
     */
    private final Node root = new Node();


    public Trie() {
        
    }
    
    public void insert(String word) {
        Node curr = root;
        for (char c : word.toCharArray()) {
            c -= 'a';
            if (curr.son[c] == null) {
                // 没有下一个节点
                curr.son[c] = new Node();
            }
            curr = curr.son[c];
        }
        curr.end = true;
    }
    
    public boolean search(String word) {
        return find(word) == 2;
    }
    
    public boolean startsWith(String prefix) {
        return find(prefix) != 0;
    }

    /**
     * 查找
     *
     * @param s s
     * @return int 0:没有找到；1：前缀匹配成功返回；2：成功
     */
    private int find(String s) {
        Node curr = root;
        for (char c : s.toCharArray()) {
            c -= 'a';
            if (curr.son[c] == null) {
                // 说明没有
                return 0;
            }
            curr = curr.son[c];
        }
        return curr.end ? 2:1;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */